<template>
    <div class="playdiaolog-box" v-if="openFlag">
      <div class="content-area-default-content mr10">
        <a href="javascript:void(0);" @click="handleClose" class="close"><i class="iconfont icon-shanchu4"></i></a>
        <ul>
          <button class=" cof flex1 text-center mainbg1 mb10" @click.prevent="handleAddVideoPart()"><i class="iconfont icon-tianjia pr tp1 mr5"></i>添加部分</button>
           <li v-for="(pitem,pindex) in videoIds">
             <div class="section-part flex justify-content-between">
               <div>
                 <input v-model="pitem.title" title="请输入章标题"  style="width: 300px;" placeholder="章标题"/>
                <span class="ml10">总数量：{{pitem.chapterList.length}}</span>
               </div>
               <div>
                 <button @click.prevent="handleAddVideo(pindex)"><i class="iconfont icon-tianjia pr tp1 mr5"></i>添加视频</button>
                 <button @click="handlePrevMain(pindex)">上移</button>
                 <button @click="handleNextMain(pindex)">下移</button>
                 <button @click="pitem.expand=!pitem.expand">{{ pitem.expand ? "展开" : "收起" }}</button>
                 <button @click="handleDelMain(pindex)">删除</button>
               </div>
             </div>
             <ul v-if="pitem.expand && pitem.chapterList && pitem.chapterList.length > 0">
               <li v-for="(item,index) in pitem.chapterList" :key="index" style="gap:5px;" class="flex mb10">
                 <input v-model="item.vid" title="视频ID" class="flex1" placeholder="视频VID" @blur="handleBlurParse(item)"/>
                 <input v-model="item.title" title="视频标题" class="flex1" placeholder="视频标题"/>
                 <input v-model="item.chapterId" title="章ID" style="width:150px;" placeholder="章ID"/>
                 <input v-model="item.lessonId" title="节ID" style="width:150px;" placeholder="节ID"/>
                 <select v-model="item.chapterId" @change="handleChangeChapter(item,$event)" class="flex1" style="width:200px;border:1px solid #eee;border-radius: 6px;">
                   <option value="">--请选择章--</option>
                   <template v-for="(chapter,index) in chapterList">
                     <option :value="chapter.id">第{{index+1}}章：{{chapter.title}}</option>
                   </template>
                 </select>
                 <select v-model="item.lessonId" @change="handleChangeLesson(item,$event)"  style="width:200px;border:1px solid #eee;border-radius: 6px;">
                   <option value="">--请选择节--</option>
                   <template v-for="(lesson,index) in lessonList">
                     <option :value="lesson.id">第{{index+1}}节：{{lesson.title}}</option>
                   </template>
                 </select>
                 <input v-model="item.duration" style="width:80px;" title="视频时长"  placeholder="视频时长"/>
                 <select  @change="handleToOther(item,pindex,index,$event)" class="flex1" style="width:200px;border:1px solid #eee;border-radius: 6px;">
                   <option value="">--请选择部分--</option>
                   <template v-for="(ppitem,ppindex) in videoIds">
                     <template v-if="pindex != ppindex">
                        <option :value="ppindex">{{ppitem.title}}</option>
                     </template>
                   </template>
                 </select>
                 <div>
                   <button @click="handleInsertBefore(pindex,index)">前插入</button>
                   <button @click="handleInsertAfter(pindex,index)">后插入</button>
                   <button @click="handlePrev(pindex,index)">上移</button>
                   <button @click="handleNext(pindex,index)">下移</button>
                   <button @click="handleDel(pindex,index)">删除</button>
                 </div>
               </li>
             </ul>
           </li>
        </ul>
        <div class="flex" style="gap: 10px;position: sticky;z-index: 100;bottom:0">
          <button class=" cof flex1 text-center mainbg1" v-if="editList.chapterId && !editList.lessonId" @click.prevent="handleEditorChapterVideo"><i class="iconfont icon-tianjia pr tp1 mr5"></i>保存章视频</button>
          <button class=" cof flex1 text-center mainbg1" v-else-if="editList.chapterId && editList.lessonId" @click.prevent="handleEditorLessonVideo"><i class="iconfont icon-tianjia pr tp1 mr5"></i>保存节视频</button>
          <button class=" cof flex1 text-center mainbg1" v-else @click.prevent="handleEditorSaveVideo"><i class="iconfont icon-tianjia pr tp1 mr5"></i>保存课程视频</button>
        </div>
      </div>
    </div>
    <div class="mask"></div>
</template>
<script setup>
  const props = defineProps({
    editObj:{
      type: Object,
      default:{}
    }
  })
  const openFlag = ref(false)
  const editList = ref(props.editObj)
  const chapterList = ref([])
  const lessonList = ref([])
  const videoIds = ref([{chapterList:[],title:"第1部分",expand:true}])


  const handleToOther = (item,pindex,index,env)=>{
    if(env.target.value){
      videoIds.value[pindex].chapterList.splice(index,1)
      videoIds.value[env.target.value].chapterList.push(item)
    }
  }

  const handleAddVideoPart = ()=>{
    var len = videoIds.value.length + 1
    videoIds.value.push({chapterList:[],title:"第"+len+"部分",expand:false})
  }
  const handleChangeChapter = (item,ev)=>{
    item.chapterId = ev.target.value
    lessonList.value = chapterList.value.find(c=>c.id ==  ev.target.value).children
  }

  const handleChangeLesson = (item,ev)=>{
    item.lessonId = ev.target.value
  }

  const handleBlurParse = async (item)=>{
    const resp = await useLoadAliplayerParseAll({vid:item.vid})
    item.duration = convertSecondsToHMS(resp.data.VideoBase.Duration)
    item.title = resp.data.VideoBase.Title
    item.url = resp.data.PlayInfoList.PlayInfo[0].PlayURL
  }

  const handleOpen = async(noteId,clist)=>{
    openFlag.value = true
    chapterList.value = clist
    editList.value.chapterId = ""
    editList.value.lessonId = ""
    const resp = await useLoadNoteDetailAll(noteId)
    var chapterListArr = resp.data.videoid ? JSON.parse(resp.data.videoid):clist
    if(chapterListArr[0].hasOwnProperty("chapterList")){
      videoIds.value = chapterListArr.map(c=>{
        c.chapterList.map(cc=>cc.url="")
        return c
      })
    }else{
      videoIds.value[0].chapterList = resp.data.videoid ? JSON.parse(resp.data.videoid):[]
    }
  }
  const handleOpenChapter = async(chapterId,clist)=>{
    openFlag.value = true
    chapterList.value = clist
    editList.value.chapterId = chapterId
    editList.value.lessonId = ""
    const resp = await useChapterGetValidatorById({"id":chapterId, "noteId":editList.value.noteId,"specialId":editList.value.specialId})
    videoIds.value = resp.data.videoid ? JSON.parse(resp.data.videoid):[]
  }

  const handleOpenLesson = async(chapterId,lessonId,clist)=>{
    openFlag.value = true
    chapterList.value = clist
    editList.value.chapterId = chapterId
    editList.value.lessonId = lessonId
    const resp = await useLessonGetValidatorById({"id":lessonId, "noteId":editList.value.noteId,"specialId":editList.value.specialId})
    videoIds.value = resp.data.videoid ? JSON.parse(resp.data.videoid):[]
  }

  const handleClose = ()=>{
    openFlag.value = false
  }
  const handleAddVideo = (pindex)=>{
    videoIds.value[pindex].expand = true
    videoIds.value[pindex].chapterList.push({title:"",vid:"",url:"",duration:"00:00",chapterId:"",lessonId:""})
  }

  const handleInsertAfter = (pindex,index)=>{
    videoIds.value[pindex].chapterList.splice(index+1,0,{title:"",vid:"",url:"",duration:"00:00",chapterId:"",lessonId:""})
  }

  const handleInsertBefore = (pindex,index)=>{
    videoIds.value[pindex].chapterList.splice(index,0,{title:"",vid:"",url:"",duration:"00:00",chapterId:"",lessonId:""})
  }

  const handleNext = (pindex,index)=>{
    var arr = videoIds.value[pindex].chapterList;
    if (index === arr.length - 1) return arr; // 已在底部，不能再下移
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]]; // 交换位置
  }
  const handlePrev = (pindex,index)=>{
    var arr = videoIds.value[pindex].chapterList;
    if (index === 0) return; // 已在顶部，不能再上移
    [arr[index - 1], arr[index]] = [arr[index], arr[index - 1]];
  }
  const handleNextMain = (index)=>{
    var arr = videoIds.value;
    if (index === arr.length - 1) return arr; // 已在底部，不能再下移
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]]; // 交换位置
  }

  const handlePrevMain = (index)=>{
    var arr = videoIds.value;
    if (index === 0) return; // 已在顶部，不能再上移
    [arr[index - 1], arr[index]] = [arr[index], arr[index - 1]];
  }

  const handleDel = (pindex,index)=>{
    videoIds.value[pindex].chapterList.splice(index, 1)
  }
  const handleDelMain = (pindex)=>{
    if(editList.value[pindex]?.chapterList?.length > 0) {
      useDialog().warning({
        content: "你确定要删除吗？",
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
          videoIds.value.splice(pindex, 1)
        },
      });
    }else{
       videoIds.value.splice(pindex, 1)
    }
  }

  // 编辑章
  const handleEditorChapterVideo = async ()=>{
    try {
      await useChapterUpdateStatus({
        id: editList.value.chapterId,
        noteId: editList.value.noteId,
        field: 'videoid',
        value: JSON.stringify(videoIds.value)
      })
      useMessage().success("保存章成功!")
    }catch (e){
      useMessage().error(e.message)
    }
  }

  const handleEditorLessonVideo = async ()=>{
    try {
      await useLessonUpdateStatus({id:editList.value.lessonId,noteId:editList.value.noteId,field:'videoid',value:JSON.stringify(videoIds.value)})
      useMessage().success("保存节成功!")
    }catch (e){
      useMessage().error(e.message)
    }
  }

  // 保存课程视频
  const handleEditorSaveVideo = async ()=>{
    try {
      await useLoadNoteUpdateVideoIdApi({id:editList.value.noteId,videoid:JSON.stringify(videoIds.value)})
      useMessage().success("保存课程视频成功!")
    }catch (e){
      useMessage().error(e.message)
    }
  }

  defineExpose({
     handleOpen,
     handleOpenChapter,
     handleOpenLesson,
     handleClose
  })

</script>
<style scoped>
.section-part{background:#eeee;padding: 10px;border-radius: 8px;margin-bottom: 10px;}
.playdiaolog-box{position: fixed;width:98%;top:40px;left: 50%;transform: translate(-50%,0%);z-index: 1001;background:#fff;padding:30px;border-radius: 8px;overflow: auto;height: 90vh;}
.playdiaolog-box .close{position:absolute;right:15px;top:10px;}
.playdiaolog-box + .mask{position: fixed;top:0;left:0;right:0;bottom: 0;background: rgba(0,0,0,0.5);z-index: 1000}
.content-area-default-content input{border:1px solid #eee;font-size:12px;}
.content-area-default-content input,.content-area-default-content button{padding:6px;border-radius: 4px;}
</style>